package com.sms.jiujia.event;

import com.sms.jiujia.model.City;
import com.sms.jiujia.model.MainData;
import com.sms.jiujia.service.LayoutConsoleLog;
import com.sms.jiujia.ui.setting.Constant;
import com.sms.jiujia.utils.*;
import com.sun.xml.internal.ws.util.StringUtils;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Pos;
import javafx.scene.Node;
import javafx.scene.control.*;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Pane;
import javafx.stage.Stage;
import javafx.util.StringConverter;
import okhttp3.Response;

import javax.swing.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.ParseException;
import java.util.Date;
import java.util.Objects;
import java.util.Optional;
import java.util.Properties;

/**
 * 按钮控制类
 *
 * @Author songmingsong
 * @Date 2023/4/28
 **/
public class HomeEvent {

    /**
     * 城市按钮
     */
    private Button btnTest;
    /**
     * 开始按钮
     */
    private Button btnStart;
    /**
     * 开始按钮
     */
    private Button reSetKeyBtn;
    /**
     * pushDeerBtn
     */
    private Button pushDeerBtn;
    /**
     * pushDeerText
     */
    private TextField pushDeerText;
    /**
     * 下拉框
     */
    private ChoiceBox<City> cityBox;
    /**
     * pushDeerBtn
     */
    private Button getKeyMethodBtn;

    /**
     * 停止按钮
     */
    private Button stopBtn;

    /**
     * 按钮初始化
     */
    public HomeEvent() {
        btnTest = Constant.setting.getBtnTest();
        btnStart = Constant.setting.getBtnStart();
        cityBox = Constant.setting.getCityBox();
        pushDeerBtn = Constant.setting.getSetPushDeerKeyBtn();
        pushDeerText = Constant.setting.getPushDeerText();
        reSetKeyBtn = Constant.setting.getReSetKeyBtn();
        getKeyMethodBtn = Constant.setting.getGetKeyMethodBtn();
        stopBtn = Constant.setting.getStopBtn();
    }

    public void init(Pane pane) {
        btnStart.setOnMouseClicked(e -> {
            if (!check()) {
                alterError("请输入key");
                LogUtils.getLayoutConsoleLogInstance().log("[error]->请输入key");
                return;
            }
            TimerTaskUtils.execute(getCurlCmd());
        });

        btnTest.setOnMouseClicked(e -> {
            LogUtils.getLayoutConsoleLogInstance().log("[info]->" + "测试推送-->");
            if (!check()) {
                alterError("请输入key");
                LogUtils.getLayoutConsoleLogInstance().log("[error]->请输入key");
                return;
            }
            String execCurlJson = UtilTools.execCurl(getCurlCmd());
            MainData mainData = UtilTools.coverJson(execCurlJson);
            Response response = null;
            try {
                response = PushMsgUtils.pushDeer(mainData, true);
            } catch (ParseException ex) {
                throw new RuntimeException(ex);
            }
            if (Objects.isNull(response)) {
                LogUtils.getLayoutConsoleLogInstance().log("[info]->" + DateUtils.changeDate(new Date()) + "数据无变化！不推送");
            }
            if (response != null && response.isSuccessful()) {
                alterSuccessful("推送成功！");
                LogUtils.getLayoutConsoleLogInstance().log("[info]->" + DateUtils.changeDate(new Date()) + "推送成功！\n" + mainData);
            }
            if (response != null && !response.isSuccessful()) {
                alterError("推送失败！请检查key或重启应用");
                LogUtils.getLayoutConsoleLogInstance().log("[info]->" + DateUtils.changeDate(new Date()) + "推送失败！请检查key或重启应用");
            }
        });
        /**
         * 城市下拉框数据转换
         */
        cityBox.setConverter(new StringConverter<City>() {
            @Override
            public String toString(City object) {
                return object.getName();
            }

            @Override
            public City fromString(String string) {
                return null;
            }
        });
        cityBox.setMaxHeight(200);
        cityBox.setMinHeight(Control.USE_COMPUTED_SIZE);

        cityBox.setTooltip(new Tooltip());
        cityBox.setOnMouseEntered(event -> {
            Node node = (Node) event.getSource();
            if (node instanceof ChoiceBox) {
                ChoiceBox<?> cb = (ChoiceBox<?>) node;
                if (cb.getItems().size() > 10) {
                    City value = (City) cb.getValue();
                    cb.getTooltip().setText(value.getName());
                    cb.getTooltip().show(node, event.getScreenX(), event.getScreenY() + 20);
                }
            }
        });

        cityBox.setOnMouseExited(event -> {
            Node node = (Node) event.getSource();
            if (node instanceof ChoiceBox) {
                ChoiceBox<?> cb = (ChoiceBox<?>) node;
                if (cb.getItems().size() > 10) {
                    cb.getTooltip().hide();
                }
            }
        });
        /**
         * 城市下拉框事件
         */
        cityBox.getSelectionModel().selectedItemProperty().addListener(new ChangeListener() {
            @Override
            public void changed(ObservableValue observable, Object oldValue, Object newValue) {
                City city = (City) newValue;
                Constant.CITY = city.getCode();
                LogUtils.getLayoutConsoleLogInstance().log("[info]->" + "选择了：" + city + "\n");
                LogUtils.getLayoutConsoleLogInstance().log("[info]->" + "当前城市代码：" + Constant.CITY);
            }
        });
        /**
         * 输入pushDeer按钮事件
         */
        pushDeerBtn.setOnAction(new EventHandler<ActionEvent>() { // 设置按钮的单击事件
            @Override
            public void handle(ActionEvent arg0) { // 处理单击事件
                DataUtil.getMData(Constant.setting.getProperties(), pushDeerText);
                HBox hbox = new HBox(); // 创建一个水平箱子
                //Label label = new Label("请输入pushKey："); // 创建一个标签
                hbox.getChildren().addAll(pushDeerText); // 给水平箱子添加一个单行输入框
                hbox.setLayoutX(15);
                hbox.setLayoutY(80);
                pane.getChildren().add(hbox); // 把水平箱子放到边界窗格的中央
            }
        });
        /**
         * pushDeer文本
         */
        pushDeerText.setOnMouseExited(e -> {
                    String key = pushDeerText.getText();
                    Constant.PUSH_DEER_KEY = key;
                    Constant.has_PUSH_DEER_KEY = true;
                    DataUtil.setMData(Constant.setting.getProperties(), pushDeerText);
                }
        );
        /**
         * 重置key
         */
        reSetKeyBtn.setOnMouseClicked(e -> {
            LogUtils.getLayoutConsoleLogInstance().log("[info]->" + "重置Key");
            Constant.PUSH_DEER_KEY = null;
            Constant.has_PUSH_DEER_KEY = false;
            pane.getChildren().add(Constant.setting.getSetPushDeerKeyBtn());
        });
        /**
         * 查看按钮
         */
        getKeyMethodBtn.setOnMouseClicked(e -> {
            LogUtils.getLayoutConsoleLogInstance().log("[info]->" + "点击了查看按钮");
            ImageIcon icon;
            try {
                icon = new ImageIcon(new URL("https://gitee.com/easychen/pushdeer/raw/main/doc/image/clipcode.png"));
            } catch (MalformedURLException ex) {
                throw new RuntimeException(ex);
            }
            JOptionPane.showMessageDialog(null, "使用方法：\n" +
                    "   ios:\n" +
                    "1、使用苹果原相机扫描该图片\n" +
                    "2、后点击屏幕上出现的pushDeer\n" +
                    "3、在弹出窗口点击打开\n" +
                    "4、进入应用后在底部找到一个名为key的小钥匙图片\n" +
                    "5、进入后，点击右上角的“+”号，就可以看到生成的key\n" +
                    "6、再将改key复制到程序中\nV 1.0 版\n版权所有：songmingsong", "pushDeerKey申请方法", -1, icon);
        });

        /**
         * 停止
         */
        stopBtn.setOnMouseClicked(e -> {
            LogUtils.getLayoutConsoleLogInstance().log("停止...");
            Constant.timer.cancel();
        });
    }


    /**
     * 窗口右上角关闭事件监听
     *
     * @param primaryStage
     */
    public void globalShutdown(Stage primaryStage) {

        TrayWindowUtil.getInstance().listen(primaryStage);
        TrayWindowUtil.getInstance().hide(primaryStage);

        //primaryStage.setOnCloseRequest(event -> {
        //    Alert alert = new Alert(Alert.AlertType.CONFIRMATION);
        //    alert.setHeaderText("最小化到托盘...");
        //    //显示提示框
        //    Optional<ButtonType> result = alert.showAndWait();
        //    if (result.get() == ButtonType.OK) {
        //        // 窗口上点击 x 或则最小化，都会触发此事件，我们不退出
        //        // 这里隐藏到托盘中
        //        TrayWindowUtil.getInstance().hide(primaryStage);
        //    } else {
        //        System.exit(0);
        //    }
        //});
    }

    /**
     * 必要参数校验
     */
    private boolean check() {
        if ("".equals(Constant.PUSH_DEER_KEY) || Objects.isNull(Constant.PUSH_DEER_KEY)) {
            return false;
        }
        return true;
    }

    private void alterError(String msg) {
        Alert alert = new Alert(Alert.AlertType.ERROR);
        alert.setHeaderText(msg);
        //显示提示框
        Optional<ButtonType> result = alert.showAndWait();
        if (result.get() == ButtonType.OK) {
        } else {
        }
    }

    private void alterSuccessful(String msg) {
        Alert alert = new Alert(Alert.AlertType.INFORMATION);
        alert.setHeaderText(msg);
        //显示提示框
        Optional<ButtonType> result = alert.showAndWait();
        if (result.get() == ButtonType.OK) {
        } else {
        }
    }

    private ProcessBuilder getCurlCmd() {
        return new ProcessBuilder("curl", "-X", "GET", "-H", "Content-Type: application/json", "https://wxapidg.bendibao.com/smartprogram/zhuanti.php?platform=wx&version=21.12.06&action=jiujia&citycode=" + Constant.CITY);
    }

}
